package com.guodi.model.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.AjaxResult;
import com.guodi.common.utils.PageData;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.model.entity.*;
import com.guodi.model.service.*;
import com.guodi.model.utils.ConvertUtil;
import com.guodi.model.utils.ExcelUtil;
import com.guodi.model.utils.JudgeWarnRuleUtil;
import com.guodi.model.utils.TimeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @描述：指标监测值表控制类
 * @作者: 彭辉
 * @日期: 2020-06-05
 */
@RestController
@RequestMapping("/IdtMonitorValue")
@Api(value = "API - IdtMonitorValueController", description = "指标监测值表")
public class IdtMonitorValueController extends BaseController {

    @Resource
    public IIdtMonitorValueService idtMonitorValueService;


    @Resource
    public IIdtIndicatorsService iIdtIndicatorsService;

    @Resource
    public IIdtReportValueService iIdtReportValueService;

    @Resource
    public IIdtTargetValueService idtTargetValueService;

    @Resource
    private IIdtWarnRuleService iIdtWarnRuleService;

    @Resource
    public IIdtYearRelevanceService iIdtYearRelevanceService;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new MyDateEditor());
    }

    private class MyDateEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if (StringUtils.isNotBlank(text)) {
                //通过两次异常的处理可以，绑定两次日期的格式
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = null;
                try {
                    date = format.parse(text);
                } catch (ParseException e) {
                    format = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        date = format.parse(text);
                    } catch (ParseException e1) {
                        e.printStackTrace();
                    }
                }
                setValue(date);
            }
        }
    }

    /**
     * @描述: 根据实体属性分页查询
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020-06-05
     **/
    @PostMapping("/listByKeyWord")
    @ApiOperation(value = " 根据关键字进行查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "long", paramType = "query", example = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示数量", required = true, dataType = "long", paramType = "query", example = "10"),
            @ApiImplicitParam(name = "keyWord", value = "关键字搜索", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份搜索", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortWay", value = "排序方式", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划代码", dataType = "string", paramType = "query")
    })
    public AjaxResult listByKeyWord(@ApiIgnore Page page, String keyWord, String year, String sort, String sortWay, String divisionCode) {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该用户所属部门不存在");
        }
        String orgId = deptId;
        HashMap map = new HashMap();
        Long start = (page.getCurrent() - 1) * page.getSize();
        Integer yearNum = null;
        if (StringUtils.isNotBlank(year)) {
            yearNum = Integer.valueOf(year);
        }
        List<IdtMonitorValue> idtYearRelevanceList = idtMonitorValueService.listByKeyWord(keyWord, yearNum, page.getSize(), start, sort, sortWay, divisionCode, orgId);
        idtYearRelevanceList.parallelStream().forEach(idtMonitorValue -> {
            String divisionName = idtMonitorValueService.getNameByDivisionCode(idtMonitorValue.getDivisionCode());
            idtMonitorValue.setDivisionName(divisionName);
            // 20210806 新增指标预警
            ApiIndicatorsVal apiIndicatorsVal = iIdtIndicatorsService.getIdtVal(idtMonitorValue.getIndicatorsId(), idtMonitorValue.getMonitorTime()+"", idtMonitorValue.getDivisionCode(), false, false);
            if(null != apiIndicatorsVal && StringUtils.isNotBlank(apiIndicatorsVal.getWarnRuleConfig())){
                String warnStatus = iIdtIndicatorsService.updateWarnStatus(apiIndicatorsVal);
                idtMonitorValue.setWarnStatus(warnStatus);
            }else {
                idtMonitorValue.setWarnStatus("null,尚未配置规则");
            }
            // 20230425 计算评估规则配置
            String estimateStatus = idtMonitorValueService.getEstimateStatus(null,idtMonitorValue.getIndicatorsId(),idtMonitorValue.getMonitorValue(),String.valueOf(idtMonitorValue.getYear()),idtMonitorValue.getDivisionCode());
            idtMonitorValue.setEstimateStatus(estimateStatus);
        });
        Integer selectCount = idtMonitorValueService.listByKeyWordAndCodeCount(keyWord, yearNum, divisionCode, orgId);
        map.put("records", idtYearRelevanceList);
        map.put("total", selectCount);
        map.put("size", page.getSize());
        map.put("current", page.getCurrent());
        map.put("searchCount", true);
        map.put("pages", selectCount % page.getSize() == 0 ? selectCount / page.getSize() : selectCount / page.getSize() + 1);
        return new AjaxResult(map);
    }

    /**
     * @描述: 根据主键查询
     * @入参:
     * @出参:
     * @作者: 彭辉
     * @日期: 2020-06-05
     **/
    @PostMapping("/findById")
    @ApiOperation(value = "根据主键查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public AjaxResult findById(String id) {
        if (StringUtils.isBlank(id)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "id不能为空");
        }
        IdtMonitorValue idtMonitorValue = idtMonitorValueService.getById(id);
        return new AjaxResult(idtMonitorValue);
    }

    /**
     * @描述: 新增
     * @入参:
     * @出参:
     * @作者: 彭辉
     * @日期: 2020-06-05
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "monitorValue", value = "监测值", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "monitorTime", value = "监测时间", required = true, dataType = "date", paramType = "query"),
            @ApiImplicitParam(name = "warnStatus", value = "预警状态", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "indicatorsId", value = "指标id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "explain", value = "指标说明", required = false, dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult save(IdtMonitorValue idtMonitorValue) {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "改用户所属部门不存在");
        }
        //相同指标不允许添加相同的监测年份、相同行政区划以及监测时间
        LambdaQueryWrapper<IdtMonitorValue> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(IdtMonitorValue::getIndicatorsId, idtMonitorValue.getIndicatorsId());
        queryWrapper.eq(IdtMonitorValue::getYear, idtMonitorValue.getYear());
        queryWrapper.eq(IdtMonitorValue::getDivisionCode, idtMonitorValue.getDivisionCode());
        queryWrapper.eq(IdtMonitorValue::getMonitorTime, idtMonitorValue.getMonitorTime());
        /* //采集时间精确到天 根据天查
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        queryWrapper.apply("to_char(GATHER_TIME,'YYYY-MM-DD') = '" + format.format(idtMonitorValue.getGatherTime())+"'");*/
        List<IdtMonitorValue> list = idtMonitorValueService.list(queryWrapper);
        if (list.size() > 0) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该指标所处年份、监测时间、行政区划监测值已存在");
        }
        // 获取预警状态，并赋值
        String warnStatus = this.idtMonitorValueService.getWarnStatus(idtMonitorValue.getIndicatorsId(), idtMonitorValue.getMonitorValue(), idtMonitorValue.getMonitorTime(), idtMonitorValue.getDivisionCode());
        idtMonitorValue.setWarnStatus(warnStatus);

        prepareData(idtMonitorValue, true);
        // 处理行政区划代码位数问题
        //idtMonitorValue.setDivisionCode(idtMonitorValue.getDivisionCode().length() == 2 ? idtMonitorValue.getDivisionCode() + "0000" : idtMonitorValue.getDivisionCode().length() == 4 ? idtMonitorValue.getDivisionCode() + "00" : idtMonitorValue.getDivisionCode());
        idtMonitorValue.setDivisionCode(idtMonitorValue.getDivisionCode());
        idtMonitorValue.setId(UuidUtil.get32UUID());
        String divisionName = idtMonitorValueService.getNameByDivisionCode(idtMonitorValue.getDivisionCode());
        idtMonitorValue.setDivisionName(divisionName);
        //关联指标信息
        IdtIndicators idtIndicators = iIdtIndicatorsService.getById(idtMonitorValue.getIndicatorsId());
        if (idtIndicators != null) {
            idtMonitorValue.setIdtCode(idtIndicators.getCode());
            idtMonitorValue.setIdtName(idtIndicators.getName());
            idtMonitorValue.setIdtUnit(idtIndicators.getUnit());
        }
        idtMonitorValue.setOrgId(deptId);
        //设置采集时间为当前系统时间--20210814产品去掉采集时间
        //idtMonitorValue.setGatherTime(new Date());
        idtMonitorValueService.save(idtMonitorValue);
        //更新对应年份的上报值的是否统一字段
        iIdtReportValueService.updateUnify(idtMonitorValue.getIndicatorsId(), idtMonitorValue.getYear() + "", idtMonitorValue.getDivisionCode());
        // 更新指标表中的更新状态
        iIdtIndicatorsService.updateStatus(idtMonitorValue.getIndicatorsId());
        return new AjaxResult(idtMonitorValue);
    }

    /**
     * @描述:判断重复数据
     * @入参:
     * @出参:
     * @作者: 郑文彬
     * @日期: 2020/8/28 15:11
     **/
    @PostMapping("/isExistsMonitor")
    @ApiOperation(value = "判断重复数据")
    public AjaxResult isExistsMonitor(MultipartFile multipartFile) throws Exception {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该用户所属部门不存在");
        }
        if (multipartFile.isEmpty()) {
            new AjaxResult(StatusCode.ERROR_CODE_40005, "导入文件不能为空！");
        }
        // 根据上传MultipartFile对象获取excel数据集
        List<List<String>> excelList = ExcelUtil.getExcelData(multipartFile);
        if (excelList == null || excelList.size() <= 1) {
            new AjaxResult(StatusCode.ERROR_CODE_40005, "导入文件数据为空！");
        }
        // 去除数据的前后空格
        excelList.stream().forEach(rowList->{
            for(int i = 0; i < rowList.size(); i++) {
                if(rowList.get(i) == null){
                    rowList.set(i,"");
                }else{
                    rowList.set(i,rowList.get(i).trim());
                }
            }
            // 去除指标编码的小数点
            int idtCodeIndex = 0;
            if (rowList.get(idtCodeIndex).contains(".")){
                rowList.set(idtCodeIndex, rowList.get(idtCodeIndex).substring(0, rowList.get(idtCodeIndex).indexOf(".") ));
            }
            // 去除行政区划编码的小数点
            int divisionCodeIndex = 4;
            if (rowList.get(divisionCodeIndex).contains(".")){
                rowList.set(divisionCodeIndex, rowList.get(divisionCodeIndex).substring(0, rowList.get(divisionCodeIndex).indexOf(".") ));
            }
            // 去除年份的小数点
            int yearIndex = 6;
            if (rowList.get(yearIndex).contains(".")){
                rowList.set(yearIndex, rowList.get(yearIndex).substring(0, rowList.get(yearIndex).indexOf(".") ));
            }
        });
        // 重复数据
        List<IdtMonitorValue> repeatingData = new ArrayList<>();
        for (int i = 1; i < excelList.size(); i++) {
            List<String> dataList = excelList.get(i);
            // 检查监测时间是否符合规范
            this.idtMonitorValueService.checkMonitorTime(dataList.get(6), true);
            String idtCode = dataList.get(0);
            LambdaQueryWrapper<IdtIndicators> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.eq(IdtIndicators::getCode, idtCode);
            IdtIndicators idtIndicators = iIdtIndicatorsService.getOne(queryWrapper);
            IdtMonitorValue idtMonitorValue = new IdtMonitorValue();
            idtMonitorValue.setIdtCode(idtCode);
            if(StringUtils.isNotBlank(dataList.get(4))){
                // 可能读成数字了，带小数，去掉小数
                if(dataList.get(4).indexOf(".") != -1){
                    String[] str =  dataList.get(4).split("\\.");
                    idtMonitorValue.setDivisionCode(str[0]);
                }else{
                    idtMonitorValue.setDivisionCode(dataList.get(4));
                }
            }
            idtMonitorValue.setMonitorValue(dataList.get(5));
            if(StringUtils.isNotBlank(dataList.get(6))){
                idtMonitorValue.setMonitorTime(dataList.get(6));
                String year = dataList.get(6).indexOf("-") >= 0 ? dataList.get(6).substring(0, dataList.get(6).indexOf("-")) : dataList.get(6);
                year = year.substring(0, 4);
                idtMonitorValue.setYear(Integer.parseInt(year));
            }else {
                return new AjaxResult(StatusCode.ERROR_CODE_40005, "第"+i+1+"行监测时间不能为空，请检查");
            }
            //dtMonitorValue.setWarnStatus(dataList.get(4));
            idtMonitorValue.setId(UuidUtil.get32UUID());
            idtMonitorValue.setOrgId(deptId);
            idtMonitorValue.setDivisionName(dataList.get(3));
            if (idtIndicators != null) {
                //判断是否存在相同指标id与行政区划编码与相同年份
                LambdaQueryWrapper<IdtMonitorValue> queryWrapper1 = new QueryWrapper().lambda();
                queryWrapper1.eq(IdtMonitorValue::getYear, idtMonitorValue.getYear());
                queryWrapper1.eq(IdtMonitorValue::getDivisionCode, idtMonitorValue.getDivisionCode());
                queryWrapper1.eq(IdtMonitorValue::getIndicatorsId, idtIndicators.getId());
                queryWrapper1.eq(IdtMonitorValue::getMonitorTime, idtMonitorValue.getMonitorTime());
                List<IdtMonitorValue> sourceIdtMonitorValueList = idtMonitorValueService.list(queryWrapper1);
                if (sourceIdtMonitorValueList.size() > 0) {
                    repeatingData.add(idtMonitorValue);
                }
            }
        }
        String resultCodes = "";
        for (IdtMonitorValue obj : repeatingData) {
            if (!resultCodes.contains(obj.getIdtCode())) {
                resultCodes += StringUtils.isBlank(resultCodes) ? obj.getIdtCode() : "," + obj.getIdtCode();
            }
        }
        return new AjaxResult(resultCodes);
    }
    /**
     * @描述:导入Excel
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/15 19:03
     **/
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入Excel")
    public AjaxResult importExcel(MultipartFile multipartFile, Boolean isUpdate) throws ParseException {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该用户所属部门不存在");
        }
        if (multipartFile.isEmpty()) {
            new AjaxResult(StatusCode.ERROR_CODE_40005, "导入文件不能为空！");
        }
        // 根据上传MultipartFile对象获取excel数据集
        List<List<String>> excelList = ExcelUtil.getExcelData(multipartFile);
        if (excelList == null || excelList.size() <= 1) {
            new AjaxResult(StatusCode.ERROR_CODE_40005, "导入文件数据为空！");
        }
        // 去除数据的前后空格
        excelList.stream().forEach(rowList->{
            for(int i = 0; i < rowList.size(); i++) {
                if(rowList.get(i) == null){
                    rowList.set(i,"");
                }else{
                    rowList.set(i,rowList.get(i).trim());
                }
            }
            // 去除指标编码的小数点
            int idtCodeIndex = 0;
            if (rowList.get(idtCodeIndex).contains(".")){
                rowList.set(idtCodeIndex, rowList.get(idtCodeIndex).substring(0, rowList.get(idtCodeIndex).indexOf(".") ));
            }
            // 去除行政区划编码的小数点
            int divisionCodeIndex = 4;
            if (rowList.get(divisionCodeIndex).contains(".")){
                rowList.set(divisionCodeIndex, rowList.get(divisionCodeIndex).substring(0, rowList.get(divisionCodeIndex).indexOf(".") ));
            }
            // 去除年份的小数点
            int yearIndex = 6;
            if (rowList.get(yearIndex).contains(".")){
                rowList.set(yearIndex, rowList.get(yearIndex).substring(0, rowList.get(yearIndex).indexOf(".") ));
            }
        });
        // 存储新增、更新指标集合
        List<IdtMonitorValue> saveUpdateList = new ArrayList<>();
        String indicatorsId = "";
        List<IdtYearRelevance> yearRelevanceList = iIdtYearRelevanceService.list();
        List<IdtTargetValue> targetValueList = idtTargetValueService.list();
        for (int i = 1; i < excelList.size(); i++) {
            List<String> dataList = excelList.get(i);
            // 检查监测时间是否符合规范
            this.idtMonitorValueService.checkMonitorTime(dataList.get(6), true);
            String idtCode = dataList.get(0);
            // 防止前端是数值格式，导致后面加.0，导致无法匹配指标
            if (idtCode.indexOf(".") != -1) {
                idtCode = idtCode.substring(0, idtCode.indexOf("."));
            }
            LambdaQueryWrapper<IdtIndicators> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.eq(IdtIndicators::getCode, idtCode);
            IdtIndicators idtIndicators = iIdtIndicatorsService.getOne(queryWrapper);
            IdtMonitorValue idtMonitorValue = new IdtMonitorValue();
            String year = dataList.get(6).indexOf("-") >= 0 ? dataList.get(6).substring(0, dataList.get(6).indexOf("-")) : dataList.get(6);
            year = year.substring(0, 4);
            idtMonitorValue.setYear(Integer.parseInt(year));
            if(StringUtils.isNotBlank(dataList.get(4))){
                //可能读成数字了，带小数，去掉小数
                if(dataList.get(4).indexOf(".") != -1){
                    String[] str =  dataList.get(4).split("\\.");
                    idtMonitorValue.setDivisionCode(str[0]);
                }else{
                    idtMonitorValue.setDivisionCode(dataList.get(4));
                }
            }
            idtMonitorValue.setMonitorValue(dataList.get(5));
            idtMonitorValue.setId(UuidUtil.get32UUID());
            idtMonitorValue.setOrgId(deptId);
            idtMonitorValue.setDivisionName(dataList.get(3));
            idtMonitorValue.setExplain(dataList.get(7));
            if (idtIndicators != null) {
                //判断是否存在相同指标id与行政区划编码与相同年份
                LambdaQueryWrapper<IdtMonitorValue> queryWrapper1 = new QueryWrapper().lambda();
                queryWrapper1.eq(IdtMonitorValue::getYear, idtMonitorValue.getYear());
                queryWrapper1.eq(IdtMonitorValue::getDivisionCode, idtMonitorValue.getDivisionCode());
                queryWrapper1.eq(IdtMonitorValue::getIndicatorsId, idtIndicators.getId());
                // 做非空及数字校验
                if(StringUtils.isNotBlank(dataList.get(5))){
                    Boolean isNum = ConvertUtil.isNumeric(dataList.get(5));
                    if (!isNum) {
                        return new AjaxResult(StatusCode.ERROR_CODE_40005, "第"+(i+1)+"行监测值不正确，请检查");
                    }
                }
                if(StringUtils.isNotBlank(dataList.get(6))){
                    String monitorTime = dataList.get(6).indexOf(".") >= 0 ? dataList.get(6).substring(0, dataList.get(6).indexOf(".")) : dataList.get(6);
                    if (StringUtils.isNotBlank(idtIndicators.getUpdateCycle())) {
                        if(!TimeUtils.verifyUpdateTime(idtIndicators.getUpdateCycle(), monitorTime)){
                            return new AjaxResult(StatusCode.ERROR_CODE_40005, "第"+(i+1)+"行监测时间格式不正确，请检查");
                        }
                    }
                    idtMonitorValue.setMonitorTime(monitorTime);
                }
                //监测时间精确到天 根据天查
                if(idtMonitorValue.getMonitorTime()!=null){
                    queryWrapper1.eq(IdtMonitorValue::getMonitorTime, idtMonitorValue.getMonitorTime());
                }
                List<IdtMonitorValue> sourceIdtMonitorValueList = idtMonitorValueService.list(queryWrapper1);
                if (sourceIdtMonitorValueList.size() > 0) {
                    if(isUpdate != null && isUpdate){
                        IdtMonitorValue monitorValue = sourceIdtMonitorValueList.get(0);
                        monitorValue.setMonitorValue(idtMonitorValue.getMonitorValue());
                        monitorValue.setExplain(idtMonitorValue.getExplain());
                        idtMonitorValue = monitorValue;
                    }else{
                        continue;
                    }
                }
                idtMonitorValue.setIndicatorsId(idtIndicators.getId());
                idtMonitorValue.setIdtCode(idtIndicators.getCode());
                idtMonitorValue.setIdtName(idtIndicators.getName());
                idtMonitorValue.setIdtUnit(idtIndicators.getUnit());
                prepareData(idtMonitorValue, true);

                //查询预警规则
                IdtWarnRule warnRule = iIdtWarnRuleService.listWarnRuleById(idtMonitorValue.getIndicatorsId());
                String warnName = JudgeWarnRuleUtil.getWarnName(yearRelevanceList, targetValueList, warnRule, idtMonitorValue.getMonitorValue(), idtMonitorValue.getYear(), idtMonitorValue.getDivisionCode(), idtMonitorValue.getIndicatorsId());
                idtMonitorValue.setWarnStatus(warnName);
                // 2021-12-24 过滤掉excel表里面【指标id、行政区划、年份、监测时间】相同的记录
                IdtMonitorValue temp = idtMonitorValue;
                saveUpdateList = saveUpdateList.stream().filter(mv -> {
                    return !(Objects.equals(mv.getIndicatorsId(), temp.getIndicatorsId())
                            && Objects.equals(mv.getYear(), temp.getYear())
                            && Objects.equals(mv.getMonitorTime(), temp.getMonitorTime())
                            && Objects.equals(mv.getDivisionCode(), temp.getDivisionCode()));
                }).collect(Collectors.toList());
                saveUpdateList.add(idtMonitorValue);
                // 存储需要更新的指标
                indicatorsId += idtIndicators.getId();
                indicatorsId += ",";
            }
        }
        if (saveUpdateList.size() > 0) {
            // 批量保存更新
            idtMonitorValueService.saveOrUpdateBatch(saveUpdateList);
            //修改统一率字段
            for (IdtMonitorValue idtMonitorValue: saveUpdateList) {
                //更新对应年份的上报值的是否统一字段
                iIdtReportValueService.updateUnify(idtMonitorValue.getIndicatorsId(), idtMonitorValue.getYear() + "", idtMonitorValue.getDivisionCode());
            }
            // 更新指标表中的更新状态
            iIdtIndicatorsService.updateStatus(indicatorsId.substring(0, indicatorsId.length() - 1));
        } else {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "导入模板缺失数据或指标编码不存在！");
        }
        return new AjaxResult(saveUpdateList);
    }

    /**
     * @描述:导出Excel
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/18 10:20
     **/
    @PostMapping("/exportExcel")
    @ApiOperation(value = "导出指标Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "exportType", value = "导出类型,传入all默认导出全部,否则根据,分隔删除", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "ids", value = "导出指标id集合", required = false, dataType = "string", paramType = "query")
    })
    public void exportExcel(String exportType, String ids) {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return;
        }
        String orgId = deptId;
        List<IdtMonitorValue> list;
        //查询指标信息子项信息
        List<IdtIndicators> idtIndicatorsList;
        List<String> stringIdList = new ArrayList<>();
        if ("all".equals(exportType)) {
            // 导出所有指标
            LambdaQueryWrapper<IdtMonitorValue> queryWrapper = new QueryWrapper().lambda();
            // 因为查看时，没有和机构挂钩，故导出时导出所有。 2020-12-31 汤厚韬
            // queryWrapper.eq(IdtMonitorValue::getOrgId, orgId);
            queryWrapper.orderByAsc(IdtMonitorValue::getMonitorTime);
            list = idtMonitorValueService.list(queryWrapper);
        } else {
            List<String> idsList = Arrays.asList(ids.split(","));
            // 导出选中指标
            LambdaQueryWrapper<IdtMonitorValue> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.orderByAsc(IdtMonitorValue::getMonitorTime);
            queryWrapper.in(IdtMonitorValue::getId, idsList);
            list = idtMonitorValueService.list(queryWrapper);
        }
        for (int z = 0; z < list.size(); z++) {
            stringIdList.add(list.get(z).getIndicatorsId());
        }
        //指标子项信息
        idtIndicatorsList = iIdtIndicatorsService.list();
        //赋值指标相关子项信息
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < idtIndicatorsList.size(); j++) {
                if (list.get(i).getIndicatorsId().equals(idtIndicatorsList.get(j).getId())) {
                    IdtIndicators idtIndicators = idtIndicatorsList.get(j);
                    list.get(i).setIdtUnit(idtIndicators.getUnit());
                    list.get(i).setIdtName(idtIndicators.getName());
                    list.get(i).setIdtCode(idtIndicators.getCode());
                    String divisionName = idtMonitorValueService.getNameByDivisionCode(list.get(i).getDivisionCode());
                    list.get(i).setDivisionName(divisionName);
                }
            }
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        for (int i = 0; i < list.size(); i++) {
            IdtMonitorValue idtMonitorValue = list.get(i);
            Object[] datas = new Object[9];
            datas[0] = idtMonitorValue.getIdtCode();
            datas[1] = idtMonitorValue.getIdtName();
            datas[2] = idtMonitorValue.getIdtUnit();
            datas[3] = idtMonitorValue.getDivisionName();
            datas[4] = idtMonitorValue.getDivisionCode();
            datas[5] = idtMonitorValue.getMonitorValue();
            datas[6] = idtMonitorValue.getMonitorTime();
            datas[7] = idtMonitorValue.getExplain();
            dataList.add(datas);
        }
        // 导出Excel
        String[] titles = {"指标编号", "指标名称", "单位", "行政区划名称", "行政区划代码", "监测值", "监测时间","指标说明"};
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        ExcelUtil.exportExcel(response, "监测指标", "监测指标信息", titles, dataList);
    }

    /**
     * @描述: 修改
     * @入参:
     * @出参:
     * @作者: 彭辉
     * @日期: 2020-06-05
     **/
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult update(IdtMonitorValue idtMonitorValue) {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "改用户所属部门不存在");
        }
        //相同指标不允许添加相同的监测年份、监测时间以及同个行政区划
        LambdaQueryWrapper<IdtMonitorValue> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(IdtMonitorValue::getIndicatorsId, idtMonitorValue.getIndicatorsId());
        queryWrapper.eq(IdtMonitorValue::getYear, idtMonitorValue.getYear());
        queryWrapper.eq(IdtMonitorValue::getDivisionCode, idtMonitorValue.getDivisionCode());
        queryWrapper.ne(IdtMonitorValue::getId, idtMonitorValue.getId());
        //采集时间精确到天 根据天查
        /*SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        queryWrapper.apply("to_char(GATHER_TIME,'YYYY-MM-DD') = '" + format.format(idtMonitorValue.getGatherTime())+"'");*/
        queryWrapper.eq(IdtMonitorValue::getMonitorTime, idtMonitorValue.getMonitorTime());
        List<IdtMonitorValue> list = idtMonitorValueService.list(queryWrapper);
        if (list.size() > 0) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该指标所处年份、监测时间、行政区划监测值已存在");
        }
        // 更新预警状态
        String warnStatus = this.idtMonitorValueService.getWarnStatus(idtMonitorValue.getIndicatorsId(), idtMonitorValue.getMonitorValue(), idtMonitorValue.getMonitorTime(), idtMonitorValue.getDivisionCode());
        idtMonitorValue.setWarnStatus(warnStatus);

        prepareData(idtMonitorValue, false);
        idtMonitorValue.setOrgId(deptId);
        idtMonitorValueService.updateById(idtMonitorValue);
        //更新对应年份的上报值的是否统一字段
        iIdtReportValueService.updateUnify(idtMonitorValue.getIndicatorsId(), idtMonitorValue.getYear() + "", idtMonitorValue.getDivisionCode());
        // 更新指标状态
        iIdtIndicatorsService.updateStatus(idtMonitorValue.getIndicatorsId());
        return new AjaxResult(idtMonitorValue);
    }

    /**
     * @描述: 根据主键删除
     * @入参: id
     * @出参:
     * @作者: 彭辉
     * @日期: 2020-06-05
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据主键删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor=Exception.class)
    public AjaxResult delete(String id) {
        if (StringUtils.isBlank(id)) {
            new AjaxResult(StatusCode.ERROR_CODE_40005, "请输入id参数");
        }
        IdtMonitorValue idtMonitorValue = idtMonitorValueService.getById(id);
        idtMonitorValueService.removeById(id);
        //更新对应年份的上报值的是否统一字段
        iIdtReportValueService.updateUnify(idtMonitorValue.getIndicatorsId(), idtMonitorValue.getYear() + "", idtMonitorValue.getDivisionCode());
        //更新指标状态
        iIdtIndicatorsService.updateStatus(idtMonitorValue.getIndicatorsId());
        return new AjaxResult();
    }

    /**
     * @描述:删除多条记录
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/6/15 16:55
     **/
    @PostMapping("/deleteByIds")
    @ApiOperation(value = "根据多个id删除,多个id用,隔开")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor=Exception.class)
    public AjaxResult deleteByIds(String ids) {
        if (StringUtils.isBlank(ids)) {
            new AjaxResult(StatusCode.ERROR_CODE_40005, "请输入ids参数");
        }
        String[] idsAry = ids.split(",");
        List<String> idList = Arrays.asList(idsAry);
        Collection<IdtMonitorValue> idtMonitorValues = idtMonitorValueService.listByIds(idList);
        idtMonitorValueService.removeByIds(idList);
        // 更新指标状态
        List<String> stringList = idtMonitorValues.stream().map(x->x.getIndicatorsId()).collect(Collectors.toList());
        iIdtIndicatorsService.updateStatus(String.join(",", stringList));
        for (IdtMonitorValue idtMonitorValue :idtMonitorValues) {
            //更新对应年份的上报值的是否统一字段
            iIdtReportValueService.updateUnify(idtMonitorValue.getIndicatorsId(), idtMonitorValue.getYear() + "", idtMonitorValue.getDivisionCode());
        }
        return new AjaxResult();
    }


    /**
     * @描述:根据指标名称查询各个采集时间的监测值
     * @入参:
     * @出参:
     * @作者: 郑文彬
     * @日期: 2020/7/3 15:46
     **/
    @PostMapping("/listByIdtName")
    @ApiOperation(value = " 根据指标名称查询各个采集时间的各个月份的监测值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idtName", value = "指标名", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划代码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "gatherYear", value = "采集时间年份(默认传：2018)", dataType = "string", paramType = "query"),
    })
    public AjaxResult listByIdtName(String idtName, String divisionCode, Integer gatherYear) {
        String deptId = this.getUser().getDeptId();
        if (StringUtils.isBlank(deptId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该用户所属部门不存在");
        }
        LambdaQueryWrapper<IdtIndicators> lambda0 = new QueryWrapper().lambda();
        lambda0.eq(IdtIndicators::getName,idtName);
        lambda0.orderByDesc(IdtIndicators::getCreateTime);
        List<IdtIndicators> idtIndicatorsList = iIdtIndicatorsService.list(lambda0);
        IdtIndicators one = idtIndicatorsList.get(0);
        LambdaQueryWrapper<IdtMonitorValue> lambda = new QueryWrapper().lambda();
        lambda.eq(IdtMonitorValue::getIndicatorsId,one.getId());
        lambda.eq(IdtMonitorValue::getDivisionCode,divisionCode);
        lambda.orderByAsc(IdtMonitorValue::getMonitorTime);
        List<IdtMonitorValue> list = idtMonitorValueService.list(lambda);

        List<Map> result = new ArrayList();
        if(list!=null && one.getUpdateCycle().equals("month")){
            for (IdtMonitorValue idtMonitorValue: list) {
                String monitorTime = idtMonitorValue.getMonitorTime();
                if(monitorTime!=null && monitorTime.split("-").length > 1){
                    int month =  Integer.valueOf(monitorTime.split("-")[1]);
                    Integer year = Integer.valueOf(monitorTime.split("-")[0]);
                    if (gatherYear == null || gatherYear.equals(year)  ){
                        Map<String, Object> map = new HashMap<>();
                        switch (month){
                            case 1 : map.put("month","一月"); break;
                            case 2 : map.put("month","二月"); break;
                            case 3 : map.put("month","三月"); break;
                            case 4 : map.put("month","四月"); break;
                            case 5 : map.put("month","五月"); break;
                            case 6 : map.put("month","六月"); break;
                            case 7 : map.put("month","七月"); break;
                            case 8 : map.put("month","八月"); break;
                            case 9 : map.put("month","九月"); break;
                            case 10 : map.put("month","十月"); break;
                            case 11 : map.put("month","十一月"); break;
                            case 12 : map.put("month","十二月"); break;
                        }
                        map.put("monitorValue",idtMonitorValue.getMonitorValue());
                        map.put("monitorTime",idtMonitorValue.getMonitorTime());
                        result.add(map);
                    }
                }
            }
        }
        return new AjaxResult(result);
    }

    /**
     * @描述:查询父城市下的监测值
     * @入参:
     * @出参:
     * @作者: 郑文彬
     * @日期: 2020/8/12 15:25
     **/
    @PostMapping("/listMonitorValByParentCity")
    @ApiOperation(value = "查询父城市下的监测值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "指标名称", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startYear", value = "起始年份", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "endYear", value = "结束年份", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentAreaCode", value = "查询父城市下的所有的指标数值时传父城市编码", required = false, dataType = "string", paramType = "query")
    })
    public AjaxResult listMonitorValByParentCity(String name, Integer startYear, Integer endYear, String parentAreaCode) {
        HashMap hashMap = new HashMap();
        PageData pageData = new PageData();
        pageData.put("parent_area_code",parentAreaCode);
        //查询指标信息
        LambdaQueryWrapper<IdtIndicators> lambda1 = new QueryWrapper().lambda();
        lambda1.eq(IdtIndicators::getName,name);
        IdtIndicators one = iIdtIndicatorsService.getOne(lambda1);
        if(one == null){
            return  new AjaxResult();
        }
        String indicatorsId = one.getId();
        //查询子城市
        List<PageData> pdList = iIdtIndicatorsService.listDivisionByEntity(pageData);
        for (int year = startYear; year <=endYear ; year++) {
            List<IdtMonitorValue> list = new ArrayList<>();
            if(pdList!=null && pdList.size()!=0){
                for (PageData pd:pdList) {
                    String code = pd.getString("code");
                    LambdaQueryWrapper<IdtMonitorValue> lambda2 = new QueryWrapper().lambda();
                    lambda2.eq(IdtMonitorValue::getYear,year);
                    lambda2.eq(IdtMonitorValue::getDivisionCode,code);
                    lambda2.eq(IdtMonitorValue::getIndicatorsId,indicatorsId);
                    lambda2.orderByDesc(IdtMonitorValue::getYear,IdtMonitorValue::getMonitorTime);
                    //取采集时间最新的一条数据
                    List<IdtMonitorValue> monitorlist = idtMonitorValueService.list(lambda2);
                    IdtMonitorValue monitorValue = new IdtMonitorValue();
                    if(monitorlist!=null && monitorlist.size()>0){
                        monitorValue = monitorlist.get(0);
                    }
                    monitorValue.setDivisionName(pd.getString("name"));
                    monitorValue.setIdtCode(one.getCode());
                    monitorValue.setIdtName(one.getName());
                    monitorValue.setIdtUnit(one.getUnit());
                    list.add(monitorValue);
                }
            }
            hashMap.put(year,list);
        }
        return  new AjaxResult(hashMap);
    }

    /**
     * @描述:查询某城市各个年份的监测值
     * @入参:
     * @出参:
     * @作者: 郑文彬
     * @日期: 2020/8/18 9:59
     **/
    @PostMapping("/listMonitorValByCity")
    @ApiOperation(value = "查询某城市各个年份的监测值--暂时未使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "指标名称", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startYear", value = "起始年份", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "endYear", value = "结束年份", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "areaCode", value = "区域编码", required = false, dataType = "string", paramType = "query")
    })
    public AjaxResult listMonitorValByCity(String name, Integer startYear, Integer endYear, String areaCode) {
        //查询指标信息
        LambdaQueryWrapper<IdtIndicators> lambda1 = new QueryWrapper().lambda();
        lambda1.eq(IdtIndicators::getName,name);
        IdtIndicators one = iIdtIndicatorsService.getOne(lambda1);
        String indicatorsId = one.getId();

        List<IdtMonitorValue> list = new ArrayList<>();
        for (int year = startYear; year <=endYear ; year++) {
            LambdaQueryWrapper<IdtMonitorValue> lambda2 = new QueryWrapper().lambda();
            lambda2.eq(IdtMonitorValue::getYear,year);
            lambda2.eq(IdtMonitorValue::getDivisionCode,areaCode);
            lambda2.eq(IdtMonitorValue::getIndicatorsId,indicatorsId);
            lambda2.orderByDesc(IdtMonitorValue::getYear,IdtMonitorValue::getMonitorTime);
            //取采集时间最新的一条数据
            List<IdtMonitorValue> monitorlist = idtMonitorValueService.list(lambda2);
            if(monitorlist!=null && monitorlist.size()>0){
                IdtMonitorValue monitorValue = monitorlist.get(0);
                //城市名称
                String divisionName = idtMonitorValueService.getNameByDivisionCode(monitorValue.getDivisionCode());
                monitorValue.setDivisionName(divisionName);
                monitorValue.setIdtCode(one.getCode());
                monitorValue.setIdtName(one.getName());
                monitorValue.setIdtUnit(one.getUnit());
                list.add(monitorValue);
            }

        }
        return  new AjaxResult(list);
    }

    /**
     * @描述:获取监测值或评估指标值的预警状态
     * @入参:
     * @出参:
     * @作者: 郑文彬
     * @日期: 2020/8/18 9:59
     **/
    @PostMapping("/getWarnStatu")
    @ApiOperation(value = "获取监测值或评估指标值的预警状态--暂时未使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "indicatorsId", value = "指标id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "monitorTime", value = "监测时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "monitorValue", value = "监测值", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult getWarnStatu(String indicatorsId, String monitorTime, String divisionCode, String monitorValue){
        // 2021-12-30 陈宏成 重写接口
        String warnStatus = this.idtMonitorValueService.getWarnStatus(indicatorsId, monitorValue, monitorTime, divisionCode);
        return new AjaxResult(warnStatus);
    }

    @PostMapping("/listMonitorValByParentCityAndYear")
    @ApiOperation(value = "查询父城市下某一年份的监测值--暂时未使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "指标名称", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "起始年份", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentAreaCode", value = "查询父城市下的所有的指标数值时传父城市编码", required = false, dataType = "string", paramType = "query")
    })
    public AjaxResult listMonitorValByParentCityAndYear(String name, Integer year, String parentAreaCode) {
        PageData pageData = new PageData();
        pageData.put("parent_area_code",parentAreaCode);
        //查询指标信息
        LambdaQueryWrapper<IdtIndicators> lambda1 = new QueryWrapper().lambda();
        lambda1.eq(IdtIndicators::getName,name);
        IdtIndicators one = iIdtIndicatorsService.getOne(lambda1);
        String indicatorsId = one.getId();
        //查询子城市
        List<PageData> pdList = iIdtIndicatorsService.listDivisionByEntity(pageData);
        List<IdtMonitorValue> list = new ArrayList<>();
        if(pdList!=null && pdList.size()!=0){
            for (PageData pd:pdList) {
                String code = pd.getString("code");
                LambdaQueryWrapper<IdtMonitorValue> lambda2 = new QueryWrapper().lambda();
                lambda2.eq(IdtMonitorValue::getYear,year);
                lambda2.eq(IdtMonitorValue::getDivisionCode,code);
                lambda2.eq(IdtMonitorValue::getIndicatorsId,indicatorsId);
                lambda2.orderByDesc(IdtMonitorValue::getMonitorTime);
                //取采集时间最新的一条数据
                List<IdtMonitorValue> monitorlist = idtMonitorValueService.list(lambda2);
                IdtMonitorValue monitorValue = new IdtMonitorValue();
                if(monitorlist!=null && monitorlist.size()>0){
                    monitorValue = monitorlist.get(0);
                }
                monitorValue.setDivisionName(pd.getString("name"));
                monitorValue.setIdtCode(one.getCode());
                monitorValue.setIdtName(one.getName());
                monitorValue.setIdtUnit(one.getUnit());
                list.add(monitorValue);
            }
        }
        return  new AjaxResult(list);
    }

    /**
     * @描述:根据多个指标名称查询特定年份和区域的监测值
     * @入参:
     * @出参:
     * @作者: 郑文彬
     * @日期: 2020/8/18 9:59
     **/
    @PostMapping("/listMonitorValByIndicatorsNames")
    @ApiOperation(value = "根据多个指标名称查询特定年份和区域的监测值--暂时未使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "names", value = "指标名称,多个名称按逗号隔开", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "areaCode", value = "区域编码", required = false, dataType = "string", paramType = "query")
    })
    public AjaxResult listMonitorValByIndicatorsNames(String names, Integer year, String areaCode) {
        HashMap<String,Object> hashMap = new HashMap();
        String[] split = names.split(",");
        for (String name : split) {
            //查询指标信息
            LambdaQueryWrapper<IdtIndicators> lambda1 = new QueryWrapper().lambda();
            lambda1.eq(IdtIndicators::getName,name);
            IdtIndicators one = iIdtIndicatorsService.getOne(lambda1);
            if (one != null){
                String indicatorsId = one.getId();
                LambdaQueryWrapper<IdtMonitorValue> lambda2 = new QueryWrapper().lambda();
                lambda2.eq(IdtMonitorValue::getYear,year);
                lambda2.eq(IdtMonitorValue::getDivisionCode,areaCode);
                lambda2.eq(IdtMonitorValue::getIndicatorsId,indicatorsId);
                lambda2.orderByDesc(IdtMonitorValue::getYear,IdtMonitorValue::getMonitorTime);
                IdtMonitorValue monitorValue = new IdtMonitorValue();
                //取采集时间最新的一条数据
                List<IdtMonitorValue> monitorlist = idtMonitorValueService.list(lambda2);
                if(monitorlist!=null && monitorlist.size()>0){
                    monitorValue = monitorlist.get(0);
                }
                //城市名称
                String divisionName = idtMonitorValueService.getNameByDivisionCode(areaCode);
                monitorValue.setDivisionName(divisionName);
                monitorValue.setIdtCode(one.getCode());
                monitorValue.setIdtName(one.getName());
                monitorValue.setIdtUnit(one.getUnit());
                hashMap.put(name,monitorValue);
            } else{
                IdtMonitorValue monitorValue = new IdtMonitorValue();
                hashMap.put(name,monitorValue);
            }


        }
        return  new AjaxResult(hashMap);
    }

    /**
    * @描述: 根据年份查询指标该更新周期下所有月度、季度数据
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2021/8/26 15:45
    **/
    @PostMapping("/listMonitorValByYear")
    @ApiOperation(value = "根据年份查询指标该更新周期下所有月度、季度数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "指标ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "updateCycle", value = "更新周期", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "区域编码", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult listMonitorValByYear(String id, String updateCycle, String year, String divisionCode) {
        List<ApiIndicatorsVal> apiIndicatorsVals = new ArrayList<>();
        if(StringUtils.isNotBlank(updateCycle) && updateCycle.equals("month")){
            // 月度 拼接查询1-12月数值
            apiIndicatorsVals = iIdtIndicatorsService.listRangeIdtVal(id, year+"-01", year+"-12", divisionCode, false, false);
        }else if(StringUtils.isNotBlank(updateCycle) && updateCycle.equals("quarter")){
            // 季度 拼接查询1-4季度数值
            apiIndicatorsVals = iIdtIndicatorsService.listRangeIdtVal(id, year+"-1", year+"-4", divisionCode, false, false);
        }
        if(apiIndicatorsVals.size() > 0){
            // 设置序号,组装返回数据格式
            AtomicInteger index = new AtomicInteger(1);
            apiIndicatorsVals.stream().forEach(x -> {
                x.setQueryTime(index+"");
                index.getAndIncrement();
            });
            // 过滤掉监测时间不存在监测值的数据
            apiIndicatorsVals = apiIndicatorsVals.stream().filter(x -> StringUtils.isNotBlank(x.getMonitorValue())).collect(Collectors.toList());
        }
        return  new AjaxResult(apiIndicatorsVals);
    }

    /**
     * @描述: 计算监测值评估规则状态
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/4/25 18:59
     **/
    @PostMapping("/getEstimateStatu")
    @ApiOperation(value = "计算监测值评估规则状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "indicatorsId", value = "指标id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "monitorTime", value = "监测时间（yyyy）", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "monitorValue", value = "监测值", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult getEstimateStatu(String indicatorsId, String monitorTime, String divisionCode, String monitorValue){
        String estimateStatus = this.idtMonitorValueService.getEstimateStatus(null,indicatorsId, monitorValue, monitorTime, divisionCode);
        return new AjaxResult(estimateStatus);
    }

    private void prepareData(IdtMonitorValue idtMonitorValue, boolean isSave) {
        if (isSave) {
            idtMonitorValue.setCreator(this.getUser().getUserId().toString());
            idtMonitorValue.setCreateTime(new Date());
            //防止误修改
            idtMonitorValue.setModifier(this.getUser().getUserId().toString());
            idtMonitorValue.setModifyTime(new Date());
        } else {
            idtMonitorValue.setModifier(this.getUser().getUserId().toString());
            idtMonitorValue.setModifyTime(new Date());
            //防止误修改
            idtMonitorValue.setCreator(null);
            idtMonitorValue.setCreateTime(null);
        }
    }
}
